package com.hxl.tech.gateway.auth.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.hxl.tech.gateway.auth.model.User;
import java.util.Date;


public class JwtUtil {

    private static final long EXPIRE_TIME = 1 * 24 * 60 * 60 * 1000;

    public static String getKeyValue(String token, String key) {
        if(token==null){
            return null;
        }
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(key).asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    public static String sign(User user, String secret) {

        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        return JWT.create()
                .withClaim("user_id", user.getUserId())
                .withClaim("user_name", user.getUserName())
                .withClaim("real_name", user.getRealName())
                .withClaim("phone", user.getPhone())
                .withClaim("role_name", user.getRoleName())
                .withClaim("system", "HXL-Gateway")
                .withExpiresAt(date)
                .sign(algorithm);
    }

}
